using Godot;
using System;

using CurrentGame.Utils.Interpolation;

namespace CurrentGame.Placements;


public partial class BreakableWall : Node2D
{
	[Export]
	public float InterpolationWeight
	{
		get => _interpolation.Weight;
		set => _interpolation.Weight = value;
	}

	private LerpInterpolation _interpolation;
	private bool _disappering = false;

	private CollisionShape2D _collisionShape;
	private Sprite2D _wallSprite;
	private GpuParticles2D _particle;


	public BreakableWall()
	{
		_interpolation = new LerpInterpolation(0.01f, new Vector3(-1f, 0.0001f, -1f))
		{
			Vector2Value = new Vector2(1.0f, 1.0f)	// alpha, white
		};
		_interpolation.Teleport();
		_interpolation.ReachStableValue += Signal_InterpolationStable;
	}

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_wallSprite = GetNode<Sprite2D>("Sprite2D");
		_particle = GetNode<GpuParticles2D>("GPUParticles2D");
		_collisionShape = GetNode<CollisionShape2D>("WallArea/CollisionShape2D");
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (_interpolation.Process(delta))
		{
			var current = _interpolation.Vector2Value;
			_wallSprite.Modulate = new Color(current.Y, current.Y, current.Y, current.X);
			_particle.Modulate = new Color(1.0f, 1.0f, 1.0f, current.X);
		}
	}

	// Export interfaces
	public void BreakWall()
	{
		if (!_disappering)
		{
			_interpolation.Vector2Value = new Vector2(0.0f, 4.0f);
			_disappering = true;
			_particle.Emitting = false;
			_collisionShape.Disabled = true;
		}
	}

	// Signals
	private void Signal_InterpolationStable(float v, Vector2 v2, Vector3 v3)
	{
		if (_disappering)
		{
			Visible = false;
			QueueFree();
		}
	}
}
